/*
	   _           _      _           _     _ 
	  (_)         | |    | |         (_)   | |
	   _ _   _ ___| |_ __| |_ __ ___  _  __| |
	  | | | | / __| __/ _` | '__/ _ \| |/ _` |
	  | | |_| \__ \ || (_| | | | (_) | | (_| |
	  | |\__,_|___/\__\__,_|_|  \___/|_|\__,_|
	 _/ |                                     
	|__/ 
	
	Copyright 2013 Caspar Isemer and and Eva Krueger, http://justdroid.org	
	
	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at
	
		http://www.apache.org/licenses/LICENSE-2.0
	
	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License. 
*/

package org.justdroid.justdroid;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class TextMessagesComposerApp extends JustDroidActivity {
	
	private Button btnTextMsgsSend;
	private TextView txtRecipient;
	private EditText editMessage;
	private String name, number, type;
	private BroadcastReceiver statusReceiver;
	
	private static final String SENT = "1";
	private static final String DELIVERED = "2";
	
	void attachKeyListener(Button button) {
		button.setOnKeyListener(new OnKeyListener() {
			
			@Override
			public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
				if(keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
					switch(keyCode) {
					case KeyEvent.KEYCODE_DPAD_CENTER:
					case KeyEvent.KEYCODE_ENTER:
						sendMessage();
						break;
					}
				}
				return false;
			}
		});
	}
	
	/** Create the Text Messages Composer activity **/
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.textmessages_composer);
		super.onCreate(savedInstanceState);
		
		statusReceiver = new BroadcastReceiver(){
			 @Override
				 public void onReceive(Context arg0, Intent arg1) {
   				 switch (getResultCode()) {
       				 case Activity.RESULT_OK:
       					 TTS.stop();
       					 if(Utils.isAccessibilityEnabled(getApplicationContext()))
       						giveFeedback(getResources().getString(R.string.smsDelivered));
       					 Toast.makeText(getApplicationContext(), getResources().getString(R.string.smsDelivered), Toast.LENGTH_SHORT).show();
       					 break;
       				 case Activity.RESULT_CANCELED:
       					 TTS.stop();
       					 if(Utils.isAccessibilityEnabled(getApplicationContext()))
       						giveFeedback(getResources().getString(R.string.smsNotDelivered));
       					 Toast.makeText(getApplicationContext(), getResources().getString(R.string.smsNotDelivered), Toast.LENGTH_SHORT).show();
       					 break;
   				 }
			 	}
			 };
			 
		// Currently, do not know how to write the code that implements text message sending
		// The picking of contacts should be similar to how it would work in ContactsApp.java
		
		/** Find UI elements **/
		btnTextMsgsSend = (Button) findViewById(R.id.btnTextMsgsSend);
	    txtRecipient = (TextView) findViewById(R.id.inputTextMessagesRecipient);
	    editMessage = (EditText) findViewById(R.id.inputTextMessagesTypedMessage);
		
	    attachListener(btnTextMsgsSend);
	    
	    if(getIntent().hasExtra("name")) {
	    	this.name = getIntent().getExtras().getString("name");
	    	this.type = getIntent().getExtras().getString("type");
	    	txtRecipient.setText(this.name + " " + this.type);
	    }
	    
	    if(getIntent().hasExtra("number")) {
	    	this.number = getIntent().getExtras().getString("number");
	    	if(txtRecipient.getText().toString().trim().equals(""))
	    		txtRecipient.setText(this.number);
	    }
	    
		/** If Send button is pressed, send the text message to the selected recipient **/
		btnTextMsgsSend.setOnClickListener(new View.OnClickListener() {
	        public void onClick(View v) {
	        	sendMessage();
	        }
	    });
		
		
		/** Put most everything before here **/
	}
	
	void sendMessage() {
		TTS.stop();
		if(Utils.isAccessibilityEnabled(getApplicationContext()))
			giveFeedback(getResources().getString(R.string.sendingSms));
		Toast.makeText(getApplicationContext(), getResources().getString(R.string.sendingSms), Toast.LENGTH_SHORT).show();
	try {
   		 
   		 PendingIntent sentPI = PendingIntent.getBroadcast(getApplicationContext(), 0,
   				 new Intent(SENT), 0);
   				 PendingIntent deliveredPI = PendingIntent.getBroadcast(getApplicationContext(), 0,new Intent(DELIVERED), 0);
   				 //---when the SMS has been sent---
   				 registerReceiver(new BroadcastReceiver(){
       				 @Override
       				 public void onReceive(Context arg0, Intent arg1) {
	        				 switch (getResultCode()) {
		        				 case Activity.RESULT_OK:
		        					 TTS.stop();
		        					 if(Utils.isAccessibilityEnabled(getApplicationContext()))
		        						 giveFeedback(getResources().getString(R.string.sentSms));
		        					 Toast.makeText(getApplicationContext(), getResources().getString(R.string.sentSms), Toast.LENGTH_SHORT).show();
		        					 break;
		        				 case SmsManager.RESULT_ERROR_NO_SERVICE:
		        					 TTS.stop();
		        					 if(Utils.isAccessibilityEnabled(getApplicationContext()))
		        						 giveFeedback(getResources().getString(R.string.noService));
		        					 Toast.makeText(getApplicationContext(), getResources().getString(R.string.noService), Toast.LENGTH_SHORT).show();
		        					 break;
		        				 case SmsManager.RESULT_ERROR_RADIO_OFF:
		        					 TTS.stop();
		        					 if(Utils.isAccessibilityEnabled(getApplicationContext()))
		        						 giveFeedback(getResources().getString(R.string.radioOff));
		        					 Toast.makeText(getApplicationContext(), getResources().getString(R.string.radioOff), Toast.LENGTH_SHORT).show();
		        					 break;
		        				 default:
		        					 TTS.stop();
		        					 if(Utils.isAccessibilityEnabled(getApplicationContext()))
		        						 giveFeedback(getResources().getString(R.string.smsNotSent));
		        					 Toast.makeText(getApplicationContext(), getResources().getString(R.string.smsNotSent), Toast.LENGTH_SHORT).show();
		        					 break;
	        				 }
       				 }
   				 }, new IntentFilter(SENT));
   				 //---when the SMS has been delivered---
   				 registerReceiver(statusReceiver, new IntentFilter(DELIVERED));
   				 SmsManager sms = SmsManager.getDefault();
   				 sms.sendTextMessage(TextMessagesComposerApp.this.number, null, editMessage.getText().toString(), sentPI, deliveredPI);
   				 
   	 }
   	 catch(Exception e) {
   		 e.printStackTrace();
   	 }
	}
	@Override
	public void onPause() {
		super.onPause();
	}
	
	@Override
	public void onResume() {
		super.onResume();
		//get the root layout
		LinearLayout layout = (LinearLayout) findViewById(R.id.textmessagescomposer);
		Utils.applyFontColorChanges(getApplicationContext(), layout);  Utils.applyFontSizeChanges(getApplicationContext(), layout);  Utils.applyFontTypeChanges(getApplicationContext(), layout);
	}
}
